import tooles from './tooles'
import CryptoJS from "crypto-js";
// const apiUrl = "http://125.77.165.192:10010";
// const apiUrl = "http://192.168.3.38:10010";

// const apiUrl = "http://192.168.3.40:10010";
// const apiUrl = "http://116.62.6.70:10010";

// 测试服务器地址
// const apiUrl = "http://125.77.165.192:10010";

// const apiUrl = "http://localhost:10010";

const apiUrl = "http://49.234.107.154:9110";

// const apiUrl = "http://192.168.3.15:9110";

const header = {
	// 'content-type': 'application/json',
	// 'content-type': 'application/json;charset=UTF-8',
	'content-type': 'application/x-www-form-urlencoded',
	// 'axh-access-token': '94eaa15cb7c8482480c0fc83ba8fadce'
	'axh-access-token': ''
}

class Request {
	constructor() {
		// 请求地址
		this.apiUrl = apiUrl
		// 请求url
		this.url = ''
		// 完整的请求地址
		this.ajaxUrl = ''
		// 请求方式
		this.method = "GET"
		// 请求参数
		this.data = null
		this.dataType = 'json'
		// 请求头
		this.header = header || {}
		// 请求拦截器
		this.beforeRequest = null
		// 响应拦截器
		this.afterRequest = null
		this.errorRequest = null
	}


	get(options = {
		url: url,
		data: data
	}) {
		this.method = "GET"
		this.url = this.apiUrl + options.url
		this.ajaxUrl = options.url
		this.data = options.data
		return this.http()
	}

	post(options = {
		url: url,
		data: data
	}) {
		this.method = "POST"
		this.url = this.apiUrl + options.url
		this.ajaxUrl = options.url,
			this.data = options.data
		return this.http()
	}


	http() {
		// 请求拦截器
		this.beforeRequest && typeof this.beforeRequest === "function" && this.beforeRequest(this)
		return new Promise((resolve, reject) => {
			let weixin = wx
			if ('undefined' !== typeof uni) {
				weixin = uni
			}
			weixin.request({
				url: this.url,
				method: this.method,
				data: this.data,
				header: this.header,
				dataType: this.dataType,
				success: (res) => {
					if (res.data && res.data.code === 200) {
						if (res.data.ase) {
							// 对Key进行排序
							let aesKey = wise.sort_ascii(res.data.aesKey);
							// 进行解密
							let aesKeyTemp = CryptoJS.enc.Utf8.parse(aesKey);
							var decrypt = CryptoJS.AES.decrypt(res.data.aesContent, aesKeyTemp, {
								mode: CryptoJS.mode.ECB,
								padding: CryptoJS.pad.Pkcs7
							});

							let pojo = JSON.parse(CryptoJS.enc.Utf8.stringify(decrypt).toString())
							resolve({
								data: pojo
							})
							return;
						}
						resolve(res.data);
					} else {

						tooles.getAlert(res.data.msg ? res.data.msg : '服务器错误，请稍后再试！')
						reject(res.data)
					}
				},
				fail: (err) => {
					reject(err)
					// 错误处理
					this.errorRequest && typeof this.errorRequest === "function" && this.errorRequest(this, err)
				},
				complete: (res) => {
					// 响应拦截器
					this.afterRequest && typeof this.afterRequest === "function" && this.afterRequest(this, res)
				}
			})
		})
	}
}

export default new Request()